<script setup>
import websocket from "@/utils/websocket";
import { useUserStore } from "./store";
import {ref,onMounted,watch} from "vue";
const userStore = useUserStore();
const userId = ref(null);

// 监视 userInfo 的变化
watch(
  () => userStore.userInfo,
  (newUserInfo, oldUserInfo) => {
    if (newUserInfo && newUserInfo.uid) {
      // 如果用户已登录且之前没有 userId，则初始化 WebSocket
      if (!oldUserInfo || oldUserInfo.uid !== newUserInfo.uid) {
        userId.value = newUserInfo.uid;
        websocket.Init(userId.value);
      }
    } 
    else if (!newUserInfo) {
      // 如果用户未登录，则关闭 WebSocket
      websocket.closeWebSocket();
    }
  },
  { deep: true } // 深度监视 userInfo 对象的变化
);

// 解决ERROR ResizeObserver loop completed with undelivered notifications.
// 限制函数执行频率
const debounce = (fn, delay) => {
  let timer = null;
  return function () {
    let context = this;
    let args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
};

const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
  constructor(callback) {
    callback = debounce(callback, 16); //16毫秒内执行一次,限制ResizeObserver的回调频率
    super(callback);
  }
};
// 读取缓存
onMounted(() => {
  userStore.fetchUserInfo();
   //  当组件挂载时，检查用户是否已登录。检查 userInfo 是否为 null
   if (userStore.userInfo) {
    userId.value = userStore.userInfo.uid;
    websocket.Init(userId.value);
  }
})
</script>
<template>
  <!--一级路由出口-->
  <router-view></router-view>
</template>
<style lang="less">
* {
  padding: 0;
  margin: 0;
}
a {
  text-decoration: none;
}
li {
  list-style: none;
}
body {
  min-width: 1400px;
}
.slick-prev,
.slick-next {
  width: 40px;
  height: 40px;
}
.slick-prev::before,
.slick-next::before {
  color: black;
  font-size: 40px;
}
.el-pagination {
  justify-content: center;
  padding: 18px 0;
  &.reply-pagination {
    justify-content: left;
  }
}
</style>
